package service

import (
	"encoding/json"
	"errors"
	"fitness/go-admin/internal/model"
	"fitness/go-admin/internal/repository"
	"fitness/go-admin/pkg/cache"
	"fitness/go-admin/pkg/logger"
	"fmt"
	"sort"
	"time"

	"gorm.io/gorm"
)

// ==================== 会员卡服务接口 ====================

type MembershipCardService interface {
	// 卡类型管理
	CreateCardType(req *model.CardTypeCreateReq) error
	UpdateCardType(id uint, req *model.CardTypeUpdateReq) error
	DeleteCardType(id uint) error
	GetCardType(id uint) (*model.MembershipCardType, error)
	ListCardTypes(cardType *model.CardType, isActive *bool, page, pageSize int) ([]model.MembershipCardType, int64, error)
	GetActiveCardTypes() ([]model.MembershipCardType, error)

	// 会员卡管理
	CreateCard(req *model.CardCreateReq, operatorID uint) (*model.MembershipCard, error)
	GetCard(id uint) (*model.MembershipCard, error)
	GetCardDetail(id uint) (*model.CardDetailResp, error)
	ListCards(memberID *uint, cardNo string, status *model.CardStatus, expireSoon int, page, pageSize int) ([]model.CardResp, int64, error)
	RenewCard(id uint, req *model.CardRenewReq, operatorID uint) error
	FreezeCard(id uint, req *model.CardFreezeReq, operatorID uint) error
	CancelCard(id uint, req *model.CardCancelReq, operatorID uint) error

	// 充值消费
	Recharge(cardID uint, req *model.RechargeReq, operatorID uint) (*model.RechargeResp, error)
	Consume(cardID uint, req *model.ConsumeReq, operatorID uint) (*model.ConsumeResp, error)

	// 查询统计
	GetBalance(cardID uint) (*model.BalanceResp, error)
	GetRechargeRecords(cardID uint, page, pageSize int) ([]model.RechargeRecord, int64, error)
	GetConsumptionRecords(cardID uint, consumeType *model.ConsumeType, page, pageSize int) ([]model.ConsumptionRecord, int64, error)
	GetBalanceLogs(cardID uint, page, pageSize int) ([]model.BalanceLog, int64, error)
	GetStatistics(cardID uint, startDate, endDate *time.Time) (*model.StatisticsResp, error)

	// 新增：获取当前用户的会员卡信息和个人交易记录
	GetMyCard(userID uint) (*model.CardDetailResp, error)
	GetMyTransactions(userID uint, page, pageSize int) ([]model.TransactionResp, int64, error)
}

type membershipCardService struct {
	db              *gorm.DB
	cardTypeRepo    repository.CardTypeRepository
	cardRepo        repository.MembershipCardRepository
	rechargeRepo    repository.RechargeRecordRepository
	consumptionRepo repository.ConsumptionRecordRepository
	balanceLogRepo  repository.BalanceLogRepository
	memberRepo      repository.MemberRepository
}

func NewMembershipCardService(
	db *gorm.DB,
	cardTypeRepo repository.CardTypeRepository,
	cardRepo repository.MembershipCardRepository,
	rechargeRepo repository.RechargeRecordRepository,
	consumptionRepo repository.ConsumptionRecordRepository,
	balanceLogRepo repository.BalanceLogRepository,
	memberRepo repository.MemberRepository,
) MembershipCardService {
	return &membershipCardService{
		db:              db,
		cardTypeRepo:    cardTypeRepo,
		cardRepo:        cardRepo,
		rechargeRepo:    rechargeRepo,
		consumptionRepo: consumptionRepo,
		balanceLogRepo:  balanceLogRepo,
		memberRepo:      memberRepo,
	}
}

// ==================== 卡类型管理 ====================

func (s *membershipCardService) CreateCardType(req *model.CardTypeCreateReq) error {
	// 验证必填字段
	if req.Type == model.CardTypeAnnual || req.Type == model.CardTypeMonthly {
		if req.ValidityDays <= 0 {
			return errors.New("年卡/月卡必须设置有效天数")
		}
	}
	if req.Type == model.CardTypeTimes {
		if req.TotalTimes <= 0 {
			return errors.New("次卡必须设置总次数")
		}
	}

	benefitsJSON, _ := json.Marshal(req.Benefits)

	cardType := &model.MembershipCardType{
		Name:          req.Name,
		Type:          req.Type,
		Price:         req.Price,
		OriginalPrice: req.OriginalPrice,
		ValidityDays:  req.ValidityDays,
		TotalTimes:    req.TotalTimes,
		Description:   req.Description,
		Benefits:      string(benefitsJSON),
		IsActive:      true,
	}

	return s.cardTypeRepo.Create(cardType)
}

func (s *membershipCardService) UpdateCardType(id uint, req *model.CardTypeUpdateReq) error {
	cardType, err := s.cardTypeRepo.GetByID(id)
	if err != nil {
		return errors.New("卡类型不存在")
	}

	if req.Name != "" {
		cardType.Name = req.Name
	}
	if req.Price > 0 {
		cardType.Price = req.Price
	}
	if req.OriginalPrice > 0 {
		cardType.OriginalPrice = req.OriginalPrice
	}
	if req.ValidityDays > 0 {
		cardType.ValidityDays = req.ValidityDays
	}
	if req.TotalTimes > 0 {
		cardType.TotalTimes = req.TotalTimes
	}
	if req.Description != "" {
		cardType.Description = req.Description
	}
	if req.Benefits != nil {
		benefitsJSON, _ := json.Marshal(req.Benefits)
		cardType.Benefits = string(benefitsJSON)
	}
	if req.IsActive != nil {
		cardType.IsActive = *req.IsActive
	}

	return s.cardTypeRepo.Update(cardType)
}

func (s *membershipCardService) DeleteCardType(id uint) error {
	return s.cardTypeRepo.Delete(id)
}

func (s *membershipCardService) GetCardType(id uint) (*model.MembershipCardType, error) {
	return s.cardTypeRepo.GetByID(id)
}

func (s *membershipCardService) ListCardTypes(cardType *model.CardType, isActive *bool, page, pageSize int) ([]model.MembershipCardType, int64, error) {
	return s.cardTypeRepo.List(cardType, isActive, page, pageSize)
}

func (s *membershipCardService) GetActiveCardTypes() ([]model.MembershipCardType, error) {
	return s.cardTypeRepo.GetActiveTypes()
}

// ==================== 会员卡管理 ====================

func (s *membershipCardService) CreateCard(req *model.CardCreateReq, operatorID uint) (*model.MembershipCard, error) {
	// 验证会员是否存在
	member, err := s.memberRepo.GetByID(req.MemberID)
	if err != nil {
		return nil, errors.New("会员不存在")
	}

	// 验证卡类型是否存在
	cardType, err := s.cardTypeRepo.GetByID(req.CardTypeID)
	if err != nil {
		return nil, errors.New("卡类型不存在")
	}

	if !cardType.IsActive {
		return nil, errors.New("该卡类型已停用")
	}

	// 解析开始日期
	startDate, err := time.Parse("2006-01-02", req.StartDate)
	if err != nil {
		return nil, errors.New("日期格式错误")
	}

	// 生成卡号
	cardNo := s.generateCardNo()

	// 创建会员卡
	card := &model.MembershipCard{
		CardNo:     cardNo,
		MemberID:   req.MemberID,
		CardTypeID: req.CardTypeID,
		Status:     model.CardStatusActive,
		StartDate:  startDate,
	}

	// 根据卡类型设置属性
	now := time.Now()
	switch cardType.Type {
	case model.CardTypeAnnual, model.CardTypeMonthly:
		expireDate := startDate.AddDate(0, 0, cardType.ValidityDays)
		card.ExpireDate = &expireDate
	case model.CardTypeTimes:
		card.RemainingTimes = cardType.TotalTimes
	case model.CardTypeStoredValue:
		card.Balance = 0.00
	}

	card.ActivatedAt = &now

	// 开始事务
	err = s.db.Transaction(func(tx *gorm.DB) error {
		// 创建会员卡
		if err := s.cardRepo.Create(card); err != nil {
			return err
		}

		// 创建充值记录（开卡充值）
		orderNo := s.generateOrderNo("RG")
		recharge := &model.RechargeRecord{
			OrderNo:       orderNo,
			CardID:        card.ID,
			MemberID:      req.MemberID,
			Amount:        req.PaymentAmount,
			BonusAmount:   0,
			ActualAmount:  req.PaymentAmount,
			PaymentMethod: req.PaymentMethod,
			PaymentStatus: model.PaymentStatusSuccess,
			OperatorID:    &operatorID,
			Remark:        fmt.Sprintf("开卡：%s - %s", member.Name, cardType.Name),
			PaidAt:        &now,
		}

		return s.rechargeRepo.Create(recharge)
	})

	if err != nil {
		return nil, err
	}

	logger.Info(fmt.Sprintf("开卡成功 - 会员:%s, 卡号:%s, 卡类型:%s", member.Name, cardNo, cardType.Name))
	return card, nil
}

func (s *membershipCardService) GetCard(id uint) (*model.MembershipCard, error) {
	return s.cardRepo.GetByIDWithRelations(id)
}

func (s *membershipCardService) GetCardDetail(id uint) (*model.CardDetailResp, error) {
	card, err := s.cardRepo.GetByIDWithRelations(id)
	if err != nil {
		return nil, errors.New("会员卡不存在")
	}

	// 获取最近的充值记录
	recentRecharges, _ := s.rechargeRepo.GetRecentByCardID(id, 5)

	// 获取最近的消费记录
	recentConsumptions, _ := s.consumptionRepo.GetRecentByCardID(id, 5)

	return &model.CardDetailResp{
		MembershipCard:     card,
		RecentRecharges:    recentRecharges,
		RecentConsumptions: recentConsumptions,
	}, nil
}

func (s *membershipCardService) ListCards(memberID *uint, cardNo string, status *model.CardStatus, expireSoon int, page, pageSize int) ([]model.CardResp, int64, error) {
	cards, total, err := s.cardRepo.List(memberID, cardNo, status, expireSoon, page, pageSize)
	if err != nil {
		return nil, 0, err
	}

	var resp []model.CardResp
	for _, card := range cards {
		var memberName, cardTypeName string
		var expireDate *string
		var daysRemaining int

		if card.Member != nil {
			memberName = card.Member.Name
		}
		if card.CardType != nil {
			cardTypeName = card.CardType.Name
		}
		if card.ExpireDate != nil {
			dateStr := card.ExpireDate.Format("2006-01-02")
			expireDate = &dateStr
			daysRemaining = int(time.Until(*card.ExpireDate).Hours() / 24)
		}

		resp = append(resp, model.CardResp{
			ID:             card.ID,
			CardNo:         card.CardNo,
			MemberName:     memberName,
			CardTypeName:   cardTypeName,
			Status:         card.Status,
			Balance:        card.Balance,
			RemainingTimes: &card.RemainingTimes,
			ExpireDate:     expireDate,
			DaysRemaining:  daysRemaining,
		})
	}

	return resp, total, nil
}

func (s *membershipCardService) RenewCard(id uint, req *model.CardRenewReq, operatorID uint) error {
	card, err := s.cardRepo.GetByID(id)
	if err != nil {
		return errors.New("会员卡不存在")
	}

	if card.Status == model.CardStatusCancelled {
		return errors.New("已注销的卡无法续费")
	}

	// 计算新的到期日期
	var newExpireDate time.Time
	if card.ExpireDate != nil && card.ExpireDate.After(time.Now()) {
		newExpireDate = card.ExpireDate.AddDate(0, 0, req.ExtendDays)
	} else {
		newExpireDate = time.Now().AddDate(0, 0, req.ExtendDays)
	}

	card.ExpireDate = &newExpireDate
	card.Status = model.CardStatusActive

	// 创建续费充值记录
	now := time.Now()
	orderNo := s.generateOrderNo("RG")
	recharge := &model.RechargeRecord{
		OrderNo:       orderNo,
		CardID:        card.ID,
		MemberID:      card.MemberID,
		Amount:        req.PaymentAmount,
		BonusAmount:   0,
		ActualAmount:  req.PaymentAmount,
		PaymentMethod: req.PaymentMethod,
		PaymentStatus: model.PaymentStatusSuccess,
		OperatorID:    &operatorID,
		Remark:        fmt.Sprintf("续卡 %d 天 - %s", req.ExtendDays, req.Remark),
		PaidAt:        &now,
	}

	return s.db.Transaction(func(tx *gorm.DB) error {
		if err := s.cardRepo.Update(card); err != nil {
			return err
		}
		return s.rechargeRepo.Create(recharge)
	})
}

func (s *membershipCardService) FreezeCard(id uint, req *model.CardFreezeReq, operatorID uint) error {
	card, err := s.cardRepo.GetByID(id)
	if err != nil {
		return errors.New("会员卡不存在")
	}

	if req.Action == "FREEZE" {
		if card.Status == model.CardStatusFrozen {
			return errors.New("会员卡已处于冻结状态")
		}
		now := time.Now()
		card.Status = model.CardStatusFrozen
		card.FrozenAt = &now
		card.FrozenReason = req.Reason
		logger.Info(fmt.Sprintf("冻结会员卡 - 卡号:%s, 原因:%s", card.CardNo, req.Reason))
	} else {
		if card.Status != model.CardStatusFrozen {
			return errors.New("会员卡未冻结")
		}
		card.Status = model.CardStatusActive
		card.FrozenAt = nil
		card.FrozenReason = ""
		logger.Info(fmt.Sprintf("解冻会员卡 - 卡号:%s", card.CardNo))
	}

	return s.cardRepo.Update(card)
}

func (s *membershipCardService) CancelCard(id uint, req *model.CardCancelReq, operatorID uint) error {
	card, err := s.cardRepo.GetByID(id)
	if err != nil {
		return errors.New("会员卡不存在")
	}

	if card.Status == model.CardStatusCancelled {
		return errors.New("会员卡已注销")
	}

	now := time.Now()
	card.Status = model.CardStatusCancelled
	card.CancelledAt = &now
	card.CancelReason = req.Reason

	// 如果有退款，记录退款
	if req.RefundAmount > 0 {
		// TODO: 处理退款逻辑
	}

	logger.Info(fmt.Sprintf("注销会员卡 - 卡号:%s, 原因:%s", card.CardNo, req.Reason))
	return s.cardRepo.Update(card)
}

// ==================== 充值消费 ====================

func (s *membershipCardService) Recharge(cardID uint, req *model.RechargeReq, operatorID uint) (*model.RechargeResp, error) {
	// 分布式锁
	lockKey := fmt.Sprintf("card:balance:lock:%d", cardID)
	if err := s.acquireLock(lockKey); err != nil {
		return nil, errors.New("系统繁忙，请稍后重试")
	}
	defer s.releaseLock(lockKey)

	card, err := s.cardRepo.GetByID(cardID)
	if err != nil {
		return nil, errors.New("会员卡不存在")
	}

	if card.Status != model.CardStatusActive {
		return nil, errors.New("会员卡状态异常，无法充值")
	}

	// 计算赠送金额（如果没有传入则根据规则计算）
	bonusAmount := req.BonusAmount
	if bonusAmount == 0 {
		bonusAmount = s.calculateBonus(req.Amount)
	}

	actualAmount := req.Amount + bonusAmount
	beforeBalance := card.Balance

	var resp *model.RechargeResp

	// 事务处理
	err = s.db.Transaction(func(tx *gorm.DB) error {
		// 1. 创建充值记录
		now := time.Now()
		orderNo := s.generateOrderNo("RG")
		recharge := &model.RechargeRecord{
			OrderNo:       orderNo,
			CardID:        cardID,
			MemberID:      card.MemberID,
			Amount:        req.Amount,
			BonusAmount:   bonusAmount,
			ActualAmount:  actualAmount,
			PaymentMethod: req.PaymentMethod,
			PaymentStatus: model.PaymentStatusSuccess,
			OperatorID:    &operatorID,
			Remark:        req.Remark,
			PaidAt:        &now,
		}

		if err := s.rechargeRepo.Create(recharge); err != nil {
			return err
		}

		// 2. 更新余额
		newBalance := beforeBalance + actualAmount
		if err := s.cardRepo.UpdateBalance(cardID, newBalance); err != nil {
			return err
		}

		// 3. 记录余额日志
		balanceLog := &model.BalanceLog{
			CardID:        cardID,
			MemberID:      card.MemberID,
			ChangeType:    model.ChangeTypeRecharge,
			Amount:        actualAmount,
			BeforeBalance: beforeBalance,
			AfterBalance:  newBalance,
			RelatedNo:     orderNo,
			OperatorID:    &operatorID,
			Remark:        req.Remark,
		}

		if err := s.balanceLogRepo.Create(balanceLog); err != nil {
			return err
		}

		resp = &model.RechargeResp{
			OrderNo:      orderNo,
			Amount:       req.Amount,
			BonusAmount:  bonusAmount,
			ActualAmount: actualAmount,
			BalanceAfter: newBalance,
			PaidAt:       now,
		}

		return nil
	})

	if err != nil {
		return nil, err
	}

	logger.Info(fmt.Sprintf("充值成功 - 卡号:%s, 充值金额:%.2f, 赠送金额:%.2f", card.CardNo, req.Amount, bonusAmount))
	return resp, nil
}

func (s *membershipCardService) Consume(cardID uint, req *model.ConsumeReq, operatorID uint) (*model.ConsumeResp, error) {
	// 分布式锁
	lockKey := fmt.Sprintf("card:balance:lock:%d", cardID)
	if err := s.acquireLock(lockKey); err != nil {
		return nil, errors.New("系统繁忙，请稍后重试")
	}
	defer s.releaseLock(lockKey)

	card, err := s.cardRepo.GetByID(cardID)
	if err != nil {
		return nil, errors.New("会员卡不存在")
	}

	if card.Status != model.CardStatusActive {
		return nil, errors.New("会员卡状态异常，无法消费")
	}

	// 获取卡类型
	cardType, err := s.cardTypeRepo.GetByID(card.CardTypeID)
	if err != nil {
		return nil, errors.New("卡类型不存在")
	}

	// 检查余额或次数
	if cardType.Type == model.CardTypeStoredValue {
		if card.Balance < req.Amount {
			return nil, errors.New("余额不足")
		}
	} else if cardType.Type == model.CardTypeTimes {
		if card.RemainingTimes < req.Times {
			return nil, errors.New("次数不足")
		}
	} else {
		// 年卡/月卡检查有效期
		if card.ExpireDate != nil && card.ExpireDate.Before(time.Now()) {
			return nil, errors.New("会员卡已过期")
		}
	}

	beforeBalance := card.Balance
	beforeTimes := card.RemainingTimes

	var resp *model.ConsumeResp

	// 事务处理
	err = s.db.Transaction(func(tx *gorm.DB) error {
		// 1. 创建消费记录
		recordNo := s.generateOrderNo("CS")
		consumption := &model.ConsumptionRecord{
			RecordNo:      recordNo,
			CardID:        cardID,
			MemberID:      card.MemberID,
			ConsumeType:   req.ConsumeType,
			RelatedID:     req.RelatedID,
			Amount:        req.Amount,
			Times:         req.Times,
			BeforeBalance: beforeBalance,
			BeforeTimes:   beforeTimes,
			OperatorID:    &operatorID,
			Remark:        req.Remark,
		}

		// 2. 更新余额或次数
		if cardType.Type == model.CardTypeStoredValue {
			newBalance := beforeBalance - req.Amount
			consumption.AfterBalance = newBalance
			if err := s.cardRepo.UpdateBalance(cardID, newBalance); err != nil {
				return err
			}

			// 记录余额日志
			balanceLog := &model.BalanceLog{
				CardID:        cardID,
				MemberID:      card.MemberID,
				ChangeType:    model.ChangeTypeConsume,
				Amount:        -req.Amount,
				BeforeBalance: beforeBalance,
				AfterBalance:  newBalance,
				RelatedNo:     recordNo,
				OperatorID:    &operatorID,
				Remark:        req.Remark,
			}
			if err := s.balanceLogRepo.Create(balanceLog); err != nil {
				return err
			}
		} else if cardType.Type == model.CardTypeTimes {
			newTimes := beforeTimes - req.Times
			consumption.AfterTimes = newTimes
			if err := s.cardRepo.UpdateRemainingTimes(cardID, newTimes); err != nil {
				return err
			}
		}

		if err := s.consumptionRepo.Create(consumption); err != nil {
			return err
		}

		resp = &model.ConsumeResp{
			RecordNo:      recordNo,
			Amount:        req.Amount,
			Times:         req.Times,
			BeforeBalance: beforeBalance,
			AfterBalance:  consumption.AfterBalance,
		}

		if cardType.Type == model.CardTypeTimes {
			resp.BeforeTimes = &beforeTimes
			resp.AfterTimes = &consumption.AfterTimes
		}

		return nil
	})

	if err != nil {
		return nil, err
	}

	logger.Info(fmt.Sprintf("消费成功 - 卡号:%s, 消费金额:%.2f, 消费次数:%d", card.CardNo, req.Amount, req.Times))
	return resp, nil
}

// ==================== 查询统计 ====================

func (s *membershipCardService) GetBalance(cardID uint) (*model.BalanceResp, error) {
	card, err := s.cardRepo.GetByID(cardID)
	if err != nil {
		return nil, errors.New("会员卡不存在")
	}

	var expireDate *string
	var daysRemaining int
	if card.ExpireDate != nil {
		dateStr := card.ExpireDate.Format("2006-01-02")
		expireDate = &dateStr
		daysRemaining = int(time.Until(*card.ExpireDate).Hours() / 24)
	}

	var remainingTimes *int
	if card.RemainingTimes > 0 {
		remainingTimes = &card.RemainingTimes
	}

	return &model.BalanceResp{
		Balance:        card.Balance,
		RemainingTimes: remainingTimes,
		ExpireDate:     expireDate,
		DaysRemaining:  daysRemaining,
		Status:         string(card.Status),
	}, nil
}

func (s *membershipCardService) GetRechargeRecords(cardID uint, page, pageSize int) ([]model.RechargeRecord, int64, error) {
	return s.rechargeRepo.GetByCardID(cardID, page, pageSize)
}

func (s *membershipCardService) GetConsumptionRecords(cardID uint, consumeType *model.ConsumeType, page, pageSize int) ([]model.ConsumptionRecord, int64, error) {
	return s.consumptionRepo.GetByCardID(cardID, consumeType, page, pageSize)
}

func (s *membershipCardService) GetBalanceLogs(cardID uint, page, pageSize int) ([]model.BalanceLog, int64, error) {
	return s.balanceLogRepo.GetByCardID(cardID, page, pageSize)
}

func (s *membershipCardService) GetStatistics(cardID uint, startDate, endDate *time.Time) (*model.StatisticsResp, error) {
	// 获取充值总额
	totalRecharge, err := s.rechargeRepo.GetTotalAmount(cardID, startDate, endDate)
	if err != nil {
		return nil, err
	}

	// 获取消费总额和记录数
	totalConsume, consumeCount, err := s.consumptionRepo.GetTotalAmountAndCount(cardID, startDate, endDate)
	if err != nil {
		return nil, err
	}

	// 按类型统计消费
	consumeByType, err := s.consumptionRepo.GetAmountByType(cardID, startDate, endDate)
	if err != nil {
		return nil, err
	}

	// 计算平均消费
	var avgConsume float64
	if consumeCount > 0 {
		avgConsume = totalConsume / float64(consumeCount)
	}

	return &model.StatisticsResp{
		TotalRecharge: totalRecharge,
		TotalConsume:  totalConsume,
		ConsumeByType: consumeByType,
		ConsumeCount:  consumeCount,
		AvgConsume:    avgConsume,
	}, nil
}

// GetMyCard 获取当前用户的会员卡信息
func (s *membershipCardService) GetMyCard(userID uint) (*model.CardDetailResp, error) {
	// 先通过userID找到对应的memberID
	member, err := s.memberRepo.GetByUserID(userID)
	if err != nil {
		return nil, errors.New("会员信息不存在")
	}

	// 获取该会员的激活状态的会员卡
	card, err := s.cardRepo.GetActiveCardByMemberID(member.ID)
	if err != nil {
		return nil, errors.New("未找到有效的会员卡")
	}

	// 获取最近5条充值记录
	recentRecharges, err := s.rechargeRepo.GetRecentRecords(card.ID, 5)
	if err != nil {
		return nil, err
	}

	// 获取最近5条消费记录
	recentConsumptions, err := s.consumptionRepo.GetRecentRecords(card.ID, 5)
	if err != nil {
		return nil, err
	}

	return &model.CardDetailResp{
		MembershipCard:     card,
		RecentRecharges:    recentRecharges,
		RecentConsumptions: recentConsumptions,
	}, nil
}

// GetMyTransactions 获取当前用户的交易记录
func (s *membershipCardService) GetMyTransactions(userID uint, page, pageSize int) ([]model.TransactionResp, int64, error) {
	// 先通过userID找到对应的memberID
	member, err := s.memberRepo.GetByUserID(userID)
	if err != nil {
		return nil, 0, errors.New("会员信息不存在")
	}

	// 获取该会员的所有会员卡ID
	cardIDs, err := s.cardRepo.GetCardIDsByMemberID(member.ID)
	if err != nil {
		return nil, 0, err
	}

	if len(cardIDs) == 0 {
		return []model.TransactionResp{}, 0, nil
	}

	// 获取交易记录（充值和消费记录合并）
	rechargeTransactions, rechargeTotal, err := s.rechargeRepo.GetTransactionsByCardIDs(cardIDs, page, pageSize)
	if err != nil {
		return nil, 0, err
	}

	// 获取消费记录
	consumptionTransactions, consumptionTotal, err := s.consumptionRepo.GetTransactionsByCardIDs(cardIDs, page, pageSize)
	if err != nil {
		return nil, 0, err
	}

	// 转换为统一的交易记录响应格式
	var result []model.TransactionResp
	for _, transaction := range rechargeTransactions {
		result = append(result, model.TransactionResp{
			ID:          transaction.ID,
			Type:        "recharge",
			TypeText:    "充值",
			Amount:      transaction.Amount,
			Balance:     0, // RechargeRecord没有AfterBalance字段
			Description: fmt.Sprintf("充值 %.2f 元", transaction.Amount),
			CreatedAt:   transaction.CreatedAt,
			RelatedNo:   transaction.OrderNo,
		})
	}

	for _, transaction := range consumptionTransactions {
		result = append(result, model.TransactionResp{
			ID:          transaction.ID,
			Type:        "consume",
			TypeText:    "消费",
			Amount:      -transaction.Amount, // 消费为负数
			Balance:     transaction.AfterBalance,
			Description: fmt.Sprintf("消费 %.2f 元", transaction.Amount),
			CreatedAt:   transaction.CreatedAt,
			RelatedNo:   transaction.RecordNo,
		})
	}

	// 按时间倒序排序
	sort.Slice(result, func(i, j int) bool {
		return result[i].CreatedAt.After(result[j].CreatedAt)
	})

	// 如果结果超过pageSize，截取前pageSize条
	if len(result) > pageSize {
		result = result[:pageSize]
	}

	// 总数为充值和消费记录的总和
	total := rechargeTotal + consumptionTotal

	return result, total, nil
}

// ==================== 辅助方法 ====================

// generateCardNo 生成卡号
func (s *membershipCardService) generateCardNo() string {
	return fmt.Sprintf("MC%s%04d", time.Now().Format("20060102"), time.Now().UnixNano()%10000)
}

// generateOrderNo 生成订单号
func (s *membershipCardService) generateOrderNo(prefix string) string {
	return fmt.Sprintf("%s%s%06d", prefix, time.Now().Format("20060102"), time.Now().UnixNano()%1000000)
}

// calculateBonus 计算充值赠送金额
func (s *membershipCardService) calculateBonus(amount float64) float64 {
	if amount >= 10000 {
		return amount * 0.20
	} else if amount >= 5000 {
		return amount * 0.15
	} else if amount >= 1000 {
		return amount * 0.10
	}
	return 0
}

// acquireLock 获取分布式锁
func (s *membershipCardService) acquireLock(key string) error {
	lockValue := "1"
	err := cache.SetWithExpire(key, lockValue, 5*time.Second)
	if err != nil {
		return errors.New("获取锁失败")
	}
	return nil
}

// releaseLock 释放分布式锁
func (s *membershipCardService) releaseLock(key string) {
	_ = cache.Delete(key)
}
